package com.itwc.websocketdemo.service;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.Set;

/**
 * WebSocket服务类 - 只管理在线用户状态
 */
@Slf4j
@Service
public class WebSocketService {
    
    private static final Logger log = LoggerFactory.getLogger(WebSocketService.class);
    
    // 存储在线用户：userId -> sessionId
    private final ConcurrentHashMap<Long, String> onlineUsers = new ConcurrentHashMap<>();
    // 反向映射：sessionId -> userId
    private final ConcurrentHashMap<String, Long> sessionToUser = new ConcurrentHashMap<>();
    
    /**
     * 用户上线
     */
    public void userOnline(Long userId, String sessionId) {
        onlineUsers.put(userId, sessionId);
        sessionToUser.put(sessionId, userId);
        log.info("用户 {} 上线，会话ID: {}", userId, sessionId);
    }
    
    /**
     * 用户下线
     */
    public void userOffline(Long userId) {
        String sessionId = onlineUsers.remove(userId);
        if (sessionId != null) {
            sessionToUser.remove(sessionId);
        }
        log.info("用户 {} 下线", userId);
    }
    
    /**
     * 根据会话ID获取用户ID
     */
    public Long getUserIdBySessionId(String sessionId) {
        return sessionToUser.get(sessionId);
    }
    
    /**
     * 根据会话ID移除用户
     */
    public Long removeUserBySessionId(String sessionId) {
        Long userId = sessionToUser.remove(sessionId);
        if (userId != null) {
            onlineUsers.remove(userId);
            log.info("通过会话ID {} 移除用户 {}", sessionId, userId);
        }
        return userId;
    }
    
    /**
     * 检查用户是否在线
     */
    public boolean isUserOnline(Long userId) {
        return onlineUsers.containsKey(userId);
    }
    
    /**
     * 获取所有在线用户ID
     */
    public Set<Long> getOnlineUserIds() {
        return onlineUsers.keySet();
    }
}